import web
import taintmode
from taintmode import *
from dyntaint import *
taintmode.ends_execution() #termina la ejecucion si un valor manchado alcanza un sumidero




urls = (
    '/', 'Index',
    '/login', 'Login',
    '/logout', 'Logout',
    '/search', 'Search',
    '/add/(\d+)','Add',
    '/del/(\d+.*)','Delete',
)

web.config.debug = False #no funcionan las sessiones con debug
app = web.application(urls, locals())

session = web.session.Session(app, web.session.DiskStore('sessions'),initializer={'logged_in':False})      

render = web.template.render('templates/')



@cleaner(SQLI)
def clsqli(a):
    return a


class Index:
    def GET(self):
        if session.get('logged_in')==True:
           
           s = db.query("SELECT id_s ,title , interpreter , duration  FROM US JOIN songs WHERE US.id_s = songs.id AND US.id_u = '%d'; "% session.get('indentifica'))
           return render.index(session.get('identifica'),session.get('username'),s)
        raise web.seeother('/login')

class Delete:
    @untrusted_args([1])
    def GET(self,song):
        s = str(song) # str no propaga la mancha !!
        wh = "id_s = " + s + " and id_u = " + str(session.get('indentifica'))
        db.delete('US' ,where= wh )
        web.redirect('/')

class Add:
    @untrusted_args([1])
    def GET(self,song):
        
        sec_id = db.insert('US' , id_s=song , id_u = session.get('indentifica') )
        web.redirect('/')


class Search:
    def POST(self):
        f = web.input().nombre
        #f = clsqli(f)
        wh = "title like '" + f + "' "
        selec= db.select('songs',where = wh)
    	return render.search(selec)



class Login:
    def GET(self):
        return render.login()
    def POST(self):
        user= web.input().user
        pas= web.input().passwd
       
        #user = clsqli(user)
        #pas = clsqli(pas)

        print 'user esta manchado? ',tainted(user)
        wh = "user_login = '" + user + "' "
        print 'wh esta manchado? ',tainted(wh)
        
        datos= db.select('members',where = wh)
        if len(datos)==0:#si no encuentra el usuario
            raise web.unauthorized()
        datos=datos[0]
        if pas == datos.user_password:#si es valido el login
            session.logged_in = True
            session.indentifica = datos.id_u
            session.username = datos.user_login
            
        raise web.seeother('/')
        
class Logout:
    def GET(self):
        session.logged_in=False        
        session.kill()
        raise web.seeother('/')


if __name__ == '__main__':
    db = web.database(dbn='mysql', user='root', pw='disenio09', db='aut')   
    
    # uso de taintmode
    
    
    web.input=untrusted(web.input)

    db.select = ssink(OSI)(db.select)
    db.insert = ssink(OSI)(db.insert)
    db.delete = ssink(OSI)(db.delete)
    db.query = ssink(OSI)(db.query)
    app.run()

